from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password,check_password
from .. import models
from . import BranchViews
import random,time,os
from web import settings
from django.core.paginator import Paginator
from django.db.models import Q
import re

# Create your views here.
# 创建后台页面的视图方法index
#后台员工管理
def index(request):

	#获取所有的员工信息
	data = models.Staff.objects.filter()

	#接受搜索条件
	selecttype = request.GET.get('selecttype',None)
	keywords = request.GET.get('keywords',None)
	if selecttype:
		#有搜索条件
		if selecttype == 'all':
			data = data.filter(
				Q(name__contains=keywords)|
				Q(phone__contains=keywords)|
				Q(homeaddress__contains=keywords)
				)
		else:
			serdata = {f"{selecttype}__contains":keywords}
			data = data.filter(**serdata)

	#实例化分页对象，参数1，数据集；参数2，每页显示的条数
	p = Paginator(data,2)

	#接受当前的页码数
	inx_p = request.GET.get('page',1)

	#获取当前页的数据
	branchlist = p.page(inx_p)

	#分配数据
	context = {'data':branchlist}

	#加载模板
	return render(request,'myadmin/staff/index.html',context)


#后台员工添加管理
def add(request):
	#查找所有员工
	types = BranchViews.selectAllTypes()
	context = {'types':types}
	return render(request,'myadmin/staff/add.html',context)

#后台员工  执行添加
def insert(request):
	data = request.POST.dict()
	data.pop('csrfmiddlewaretoken')
	data.pop('branchtypeid')
	#获取选择的分类id
	branchtypeid = request.POST.get('branchtypeid')
	# 根据分类id获取分类对象
	branchtypeobjs = models.Branchtype.objects.filter(id=branchtypeid)
	data['branchtypeid'] = branchtypeobjs[0]
	#判断手机号是否正确
	if re.findall('1\d{10}',data['phone']):
		obj = models.Staff.objects.filter(phone=data['phone'])
		if obj.count()>0:
			url = reverse('myadmin_staff_index')
			return HttpResponse(f'<script>alert("手机号已注册");location.href="{url}"</script>')
		#密码加密
		data['password']=make_password(data['password'],None,'pbkdf2_sha256')
		try:
			# 检测是否上传了头像
			file=request.FILES.get('face',None)
			if file:
				#上传了头像
				data['face']=imgupload(file)
			else:
				# data.pop('face')
				return HttpResponse(f'<script>alert("请添加头像");history.back();</script>')

			#创建书籍对象，完成添加
			obj = models.Staff(**data)
			#给书籍和分类设置关系
			# obj.branchtypeid.set(branchtypeobjs)
			obj.save()

			url = reverse('myadmin_staff_index')
			return HttpResponse(f'<script>alert("员工添加成功");location.href="{url}"</script>')
		except:
			url = reverse('myadmin_staff_add')
			return HttpResponse(f'<script>alert("员工添加失败");location.href="{url}"</script>')
	else:
		return HttpResponse('<script>alert("手机号填写有误");history.back()</script>')


#后台员工  删除
def delete(request):
	try:
		id = request.GET.get('id')
		obj = models.Staff.objects.get(id=id)
		#判断当前用户是否有上传头像
		print(obj.face)
		try:
			if 'uploads' in obj.face:
				#删除
				os.remove('.'+obj.face)
		except:
			return JsonResponse({'code':2,'msg':'头像删除失败'})
		#删除一对多外键
		models.Staff.objects.filter(id=id).delete()
		#删除用户数据
		obj.delete()
		return JsonResponse({'code':0,'msg':'删除成功'})
	except:
		return JsonResponse({'code':1,'msg':'删除失败'})


#后台员工  编辑
def edit(request, bid):
	#查找所有部门
	types = BranchViews.selectAllTypes()

	#获取当前员工信息
	staff = models.Staff.objects.get(id=bid)

	#获取当前员工的所在部门
	ts = staff.branchtypeid
	#分配数据，加载模板
	context = {'types':types,'staff':staff,'ts':ts}

	return render(request,'myadmin/staff/edit.html',context)

#后台员工  更新编辑
def update(request):
	data = request.POST.dict()
	data.pop('csrfmiddlewaretoken')
	staffid = data['id']
	#判断是否填写员工部门
	if 'branchtypeid' in data:
		data.pop('id')
		data.pop('branchtypeid')
		# 判断电话
		if re.findall('1\d{10}',data['phone']):

			#判断当前密码是否更新
			if data['password'] != data['old_password']:
				data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
			else:
				data['password']=data['old_password']
			data.pop('old_password')

			# 判断当前是否更新图片
			file = request.FILES.get('face', None)
			if file:
				# 上传了新的图片
				filename = imgupload(file)
				if 'uploads' in data['old_face']:
					# 删除原来的图片信息
					os.remove('.' + data['old_face'])
				data['face'] = filename

			else:
				# 没有上传图片
				data['face'] = data['old_face']

			# 删除原来的图片信息
			data.pop('old_face')


			# 定义跳转的列表页
			url = reverse('myadmin_staff_index')

			# 获取当前图书对象
			obj = models.Staff.objects.get(id=staffid)

			try:
				#获取选择的分类id
				branchtypeid = request.POST.get('branchtypeid')
				# 根据分类id获取分类对象
				branchtypeobjs = models.Branchtype.objects.filter(id=branchtypeid)
				data['branchtypeid'] = branchtypeobjs[0]
				# 更新图书数据
				models.Staff.objects.filter(id=staffid).update(**data)
				return HttpResponse(f'<script>alert("更新当前员工数据成功");location.href="{url}"</script>')
			except:
				return HttpResponse(f'<script>alert("更新当前员工数据失败");location.href="{url}"</script>')
		else:
			return HttpResponse('<script>alert("手机号填写有误");history.back()</script>')
	else:
		return HttpResponse('<script>alert("请填写员工部门");history.back()</script>')

#封装图片上传方法
def imgupload(file):
	try:
		filename=str(random.randint(10000,99999)+time.time())+'.'+file.name.split('.').pop()
		with open(f'./static/uploads/{filename}','wb+') as fp:
			fp.write(file.read())

		return f'/static/uploads/{filename}'
	except:
		return False


